#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include"../include/main.h"
#include"../include/bst.h"
#include"../include/makedir.h"
#include"../include/mount_vfs.h"
#include"../include/narrtree.h"
#include"../include/hash.h"
#include"../include/vfs_errorcodes.h"
#include"../include/create_vfs.h"

void makedir(char path[],char dirname[])
{
	fdesc *mkdesc,*root;
	char temp[MAX_PATH],invalid_char[]={'/'};
	llist *list;
	int i=0;
	char *t,*k;
	if(mounted == 0)
		printf("%s_FAILURE %s\n",glb_command,ERR_VFS_MAKEDIR_05);
	else if((t=strchr(dirname,invalid_char[i])) != NULL)
		printf("%s_FAILURE %s\n",glb_command,ERR_VFS_MAKEDIR_02);
	else if(local_max_fd > local_used_fd)
	{
		i=0;
		while(path[i]!='\0')
		{
			temp[i]=path[i];
			i++;
		}
		temp[i]='\0';
		//if(strcmp(path,"/"))
		//	strcat(temp,"/");
                k=strrchr(temp,'/');
		if(k!=NULL)
		{
			k++;
			if(*k != '\0')
		        strcat(temp,"/");
			strcat(temp,dirname);
			mkdesc=(fdesc *)malloc(sizeof(fdesc));
			strcpy(mkdesc->filepath,temp);
			mkdesc->filepath[strlen(mkdesc->filepath)]='\0';
			strcpy(mkdesc->filename,dirname);
			mkdesc->filename[strlen(mkdesc->filename)]='\0';
			mkdesc->filetype=1;
			mkdesc->file_size=0;
			mkdesc->blk_num=0;		
			list=insert(mkdesc);
			if(list==NULL)
				printf("%s_FAILURE %s\n",glb_command,ERR_VFS_MAKEDIR_03);
			else
			{
				if(local_used_fd == 0)
				{
					root=(fdesc *)malloc(sizeof(fdesc));
					strcpy(root->filepath,"/");
					//root->filepath[strlen(root->filepath)-1]='\0';
					strcpy(root->filename,"/");
					//root->filename[strlen(root->filename)-1]='\0';
					root->filetype=1;
					root->file_size=0;
					root->blk_num=0;
					head=create(root);
					list=insert(root);
					local_used_fd++;
					head=insert_ntree(head,mkdesc);	
				}
				else
					head=insert_ntree(head,mkdesc);
				local_used_fd++;
				printf("makedir_SUCCESS\n");
			}
		}
		else
			printf("%s_FAILURE %s\n",glb_command,ERR_VFS_MAKEDIR_02);
	}

	else
		printf("%s_FAILURE %s\n",glb_command,ERR_VFS_MAKEDIR_01);
}
